#!/usr/local/bin/python3.7
import pymysql
import time
import sys
import os
from configparser import ConfigParser
from DrissionPage import WebPage,ChromiumPage,ChromiumOptions,SessionPage

config = ConfigParser()
config.read('config.ini')
path = config.get('server','chrome_path')  # 请改为你电脑内Chrome可执行文件路径
ChromiumOptions().set_browser_path(path).save()
co = ChromiumOptions().headless() #无头浏览器
page = ChromiumPage(co)
# page = ChromiumPage()
pageSession = SessionPage()

argv_path = sys.argv[0]
if ((os.path.isfile(argv_path))):
    print(argv_path + ' 已找到，开始执行...')
else:
    print('File not exist!!!')
    sys.exit()

startTime = time.time()  # 计时开始
print('计时开始，当前时间为', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(startTime)))

def login():
    loginUrl = getconfig('server','login_url')
    # 加载界面
    page.get(loginUrl)
    
    wait = config.getint('setting','wait_seconds')
    print(f"进入登录页面等待{wait}s...")
    page.wait(20)
    
    for i in page.cookies(as_dict=False, all_domains=True):
        print(i)
    # 清空cookie
    cookie_items = pageSession.set.cookies.clear()
    
    #如果是已登录状态，则直接退出登录并关闭页面
    try:
        page.wait.ele_displayed(getconfig('target','username_ele'), timeout=None, raise_err=True)
    except:
        # 截图保存
        page.get_screenshot(path=getconfig('setting', 'login_screenshot_path'), name='islogin.jpg', full_page=True)
        print('已登录，退出页面...')
        page.quit()
        sys.exit()
    
    # 定位到账号文本框，获取文本框元素
    username = page.ele(getconfig('target','username_ele'))
    # 输入对文本框输入账号
    username.input(getconfig('target','account'))
    # 定位到密码文本框并输入密码
    password = page.ele(getconfig('target','password_ele'))
    # 输入对文本框输入密码
    password.input(getconfig('target','password'))
    # 点击登录按钮
    page.ele(getconfig('target','submit_button')).click()

    print(f"执行登录等待{wait}s...")
    page.wait(wait)
    
    # 截图保存
    page.get_screenshot(path=getconfig('setting', 'login_screenshot_path'), name=getconfig('setting', 'login_screenshot_name'), full_page=True)
    #获取cookie
    cookie_str = ''
    cookie_items = page.cookies(as_dict=False, all_domains=True)
    #组装cookie字符串
    for item_cookie in cookie_items:
        item_str = item_cookie["name"]+"="+item_cookie["value"]+"; "
        cookie_str += item_str
        if item_cookie["name"] == 'session':
            session = item_cookie["value"]
            print('session：',item_cookie["value"])
    #保存到数据库
    updateMysql(session)
    #打印出来看一下
    file = open(getconfig('setting', 'cookie_file_name'),'w')
    file.write(session)
    file.close()
    page.quit()
    
def getconfig(type, key):
    return config.get(type, key)
    
def updateMysql(session):
    dbconfig = dict(config.items('database'))
    # 数据库连接
    db = pymysql.connect(**dbconfig)

    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # SQL 更新语句
    sql = "UPDATE ht_set SET `value` = '" + session + "' WHERE `key` = 'cookie'"
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        # 发生错误时回滚
        db.rollback()

    # 关闭数据库连接
    db.close()

login()


